import WebGl from '@/modules/three';

const { Three, TWEEN, dat } = WebGl;

class WebGlControl {
  private container: any;
  private camera: any;
  private scene: any;
  private renderer: any;
  private animateFrame: any;
  private starsGroup: any; //
  private windowHalfX = window.innerWidth / 2;
  private windowHalfY = window.innerHeight / 2;

  private Geometrys: {
    cubeGeometry?: any;
    starsGeometry?: any;
  } = {}; //保存所有Geometry，方便统一销毁
  private Materials: {
    cubeMaterial?: any;
    starsMaterial?: any;
  } = {}; //保存所有Material，方便统一销毁

  private GuiInit: any = null;
  private guiData: any = {
    x: 0.005,
    color: '#f0f2f5',
    autoRotate: true,
  };
  private mouseData: any = {
    mouseX: 0,
    mouseY: 0,
  };

  public init = (id: string) => {
    // if(this.scene) {return}
    this.container = document.getElementById(id);
    let width = this.container.clientWidth,
      height = this.container.clientHeight;

    this.scene = new Three.Scene();

    this.camera = new Three.PerspectiveCamera(75, width / height, 1, 2000);
    this.camera.position.x = 0;
    this.camera.position.y = 0;
    this.camera.position.z = 500;
    this.camera.lookAt(this.scene.position);

    this.renderer = new Three.WebGLRenderer();
    // this.renderer.setClearColor( 0xffffff );
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);
    this.container.appendChild(this.renderer.domElement);

    this.addThings();
    this.addLight(); //+光源
    this.animate(); //开始动
    this.initEventListen();

    // this.initGui();
  };

  public destroy = () => {
    this.toggleGui(0);
    Object.values(this.Geometrys).forEach((e) => {
      e.dispose();
    });
    Object.values(this.Materials).forEach((e) => {
      e.dispose();
    });
    this.scene.clear();
    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.GuiInit = null;
    cancelAnimationFrame(this.animateFrame);
  };

  public initGui = () => {
    if (this.GuiInit) {
      this.toggleGui();
      return;
    }
    this.GuiInit = new dat.GUI({
      // autoPlace: false
    });

    this.GuiInit.domElement.style.position = 'absolute';
    this.GuiInit.domElement.style.right = '10px';
    this.GuiInit.domElement.style.top = '10px';

    let GuiController = this.GuiInit.addFolder('控制窗口');
    GuiController.add(this.guiData, 'x', -0.1, 0.1, 0.005).name('自转速度');
    GuiController.addColor(this.guiData, 'color').name('背景颜色');
    GuiController.open();

    let starsGui = this.GuiInit.addFolder('stars position');
    starsGui.add(this.starsGroup.position, 'x', -500, 500, 1);
    starsGui.add(this.starsGroup.position, 'y', -500, 500, 1);
    starsGui.add(this.starsGroup.position, 'z', -500, 500, 1);
    starsGui.open();

    let starsGuiRotate = this.GuiInit.addFolder('stars rotation');
    starsGuiRotate.add(this.guiData, 'autoRotate').name('自动旋转');
    starsGuiRotate.add(this.starsGroup.rotation, 'x', -3.14, 3.14, 0.01);
    starsGuiRotate.add(this.starsGroup.rotation, 'y', -3.14, 3.14, 0.01);
    starsGuiRotate.add(this.starsGroup.rotation, 'z', -3.14, 3.14, 0.01);
    //rotation是欧拉类型的值，单位是π；比如让物体按Y轴正方向旋转45°可以写成 object3D.rotation.y+=0.25*Math.PI
    starsGuiRotate.open();
  };

  public toggleGui = (state: any = null) => {
    if (!this.GuiInit || !this.GuiInit.domElement) {
      return;
    }
    let display = this.GuiInit.domElement.style.display == 'none' ? '' : 'none';
    if (state == 0) {
      display = 'none';
    }
    this.GuiInit.domElement.style.display = display;
  };

  private initEventListen = () => {
    this.container.addEventListener('pointermove', this.onPointerMove);
    window.addEventListener('resize', this.onWindowResize);
  };
  private onPointerMove = (event) => {
    if (event.isPrimary === false) return;
    this.mouseData.mouseX = event.clientX - this.container.clientWidth;
    this.mouseData.mouseY = event.clientY - this.container.clientHeight;
  };
  private onWindowResize = () => {
    this.windowHalfX = window.innerWidth / 2;
    this.windowHalfY = window.innerHeight / 2;

    // this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();

    this.renderer.setSize(window.innerWidth, window.innerHeight);
  };

  private addLight = () => {
    // let ambi = new Three.AmbientLight(0x686868);
    // this.scene.add(ambi);
    // let spotLight = new Three.DirectionalLight(0xffffff);
    // spotLight.position.set(550, 100, 550);
    // spotLight.intensity = 0.6;
    // this.scene.add(spotLight);
    // let light = new Three.PointLight( 0xFFFF00 );
    // light.position.set( -100, 100, 0 );
    // this.scene.add(light);
  };

  private addThings = () => {
    // const axesHelper = new Three.AxesHelper(800);
    // this.scene.add(axesHelper); //添加坐标轴；红线是X轴，绿线是Y轴，蓝线是Z轴

    /** 立方体 **/
    // this.Geometrys.cubeGeometry = new Three.BoxGeometry( 100, 100, 100);
    // this.Materials.cubeMaterial = new Three.MeshLambertMaterial( { color: 0xfd59d7 } );
    // const cube = new Three.Mesh( this.Geometrys.cubeGeometry, this.Materials.cubeMaterial );
    // this.scene.add( cube );
    /** 立方体 **/

    /** 星空 **/
    this.starsGroup = new Three.Group();
    this.starsGroup.position.z = -2000;
    this.scene.add(this.starsGroup);
    this.Geometrys.starsGeometry = new Three.BufferGeometry();
    let starArr: any[] = [];
    for (let i = 0; i < 2000; i++) {
      // const x = Three.MathUtils.randFloatSpread(150);
      // const y = Three.MathUtils.randFloatSpread(150);
      // const z = Three.MathUtils.randFloatSpread(150);
      const x = Math.random() * 1200 - 600;
      const y = Math.random() * 1200 - 600;
      const z = Math.random() * 1200 - 600;
      starArr.push(x, y, z);
    }
    this.Geometrys.starsGeometry.setAttribute(
      'position',
      new Three.Float32BufferAttribute(starArr, 3),
    );

    /** 创建一个圆形的材质 **/
    //记得一定要加上texture.needsUpdate = true;
    let canvDom = document.createElement('canvas');
    canvDom.width = 100;
    canvDom.height = 100;
    let context: any = canvDom.getContext('2d');
    context.fillStyle = '#ffb51c';
    context.strokeStyle = '#ffb51c';
    // http://www.w3school.com.cn/tags/canvas_arc.asp
    // context.arc(50,50,45,0,2*Math.PI);  //圆形
    context.moveTo(0, 50);
    context.bezierCurveTo(25, 50, 50, 25, 50, 0);
    context.bezierCurveTo(50, 25, 75, 50, 100, 50);
    context.bezierCurveTo(75, 50, 50, 75, 50, 100);
    context.bezierCurveTo(50, 75, 25, 50, 0, 50); //星星
    context.stroke();
    context.fill();
    /** 创建一个圆形的材质 **/

    // 创建材质
    let texture = new Three.Texture(canvDom);
    texture.needsUpdate = true;
    this.Materials.starsMaterial = new Three.PointsMaterial({
      color: 0xffb51c,
      depthTest: false,
      transparent: true,
      size: 6,
      map: texture,
    });
    const stars = new Three.Points(
      this.Geometrys.starsGeometry,
      this.Materials.starsMaterial,
    );
    this.starsGroup.add(stars);
    /** 星空 **/
  };

  public toggleTween = (z: number, callback?: () => void) => {
    // cameray: 20, z: 500
    var tween = new TWEEN.Tween(this.starsGroup.position)
      .to({ x: 0, y: 0, z }, 1000)
      .start()
      .onComplete(() => {
        if (callback) {
          callback();
        }
      });
    // tween.easing(TWEEN.Easing.Sinusoidal.InOut);
    tween.easing(TWEEN.Easing.Circular.Out);
  };

  public restartAnimate = () => {
    this.stopState = false;
    this.animate();
  };
  public stopAnimate = () => {
    this.stopState = true;
  };
  private stopState: boolean = false;
  private animate = () => {
    if (this.stopState) {
      return;
    }
    // if(!this.renderer){return;}
    this.animateFrame = requestAnimationFrame(this.animate);
    this.render();
    TWEEN.update();
  };
  private render = () => {
    if (!this.renderer) {
      return;
    }
    this.renderer.setClearColor(this.guiData.color, 1.0);
    if (this.guiData.autoRotate) {
      // this.starsGroup.rotation.x+= 0.025
      this.starsGroup.rotation.y += 0.002;
    }

    // const time = Date.now() * 0.005;
    // this.pointsGroup.rotation.y = this.guiData.x * time;
    // this.pointsGroup.rotation.z = this.guiData.x * time;

    this.camera.position.x +=
      (this.mouseData.mouseX - this.camera.position.x) * 0.025;
    this.camera.position.y +=
      (-this.mouseData.mouseY - this.camera.position.y) * 0.025;
    this.camera.lookAt(this.scene.position);
    this.renderer.render(this.scene, this.camera);
  };
}

const webGlControl = new WebGlControl();
export default webGlControl;
